#!/bin/bash
# Variables
dest="" # Need to reset to empty

# Only arg passed in is how many times to run, if blank, uses default in this script
if [ ! -z $1 ];
then
  count=$1 # $1 was given
else
  count= # $1 was not given
fi
echo "count is $count."
tmp=ssd7
threads=16
buckets=256
buckets3=${buckets}
tempdir=/${tmp}/Plotter/
pool=aab84146ce887e20318edfab1303701bdea567e1b1eda724c3a8ec390ee111321debeb792957c68c18b848d391940f47
farm=aa866b81646651062840440b9c418d5c1925a6e1b5786630534c7594a16658ca6a1cdd53ca7dba40058ba542dac16aa8
tmptoggle=false
log=/var/chia
dest1=/33
dest2=/34
declare -a final_dest=(
                       "${dest1}"
                       "${dest2}"
                      )
max=95%
farm_folder=Plots/ # disk_space check only works with mount points.

disk_space () {
   # Check drive space on dest
  for j in "${final_dest[@]}"
  do
    used=$(df -Ph | grep -G ${j} | awk {'print $5'});
     if [ ${used%?} -ge ${max%?} ];
     then
       dest=”” # In case it was set on a run and now is not valid.
       echo "The Mount Point ${j} on $(hostname) has used ${used} at $1." |tee -a ${log}/${tmp}_${1}_plot-${2}.log;
     else
       dest=${j}/${farm_folder};
       echo "New Mount Point is $dest." |tee -a ${log}/${tmp}_${1}_plot-${2}.log;
       break;
     fi
  done
}

# Main run loop
for i in $(seq 1 $count);
do

   dt=$(date '+%Y-%m-%d_%H_%M_%S');
   disk_space ${dt} ${i}
   if [[ -z $dest ]]; then
     echo "No drive space found for final destination!" |tee -a ${log}/${tmp}_${dt}_plot-${i}.log;
     exit
   fi

   # Remove any tmp files leftover
   rm -rf ${tempdir}*.tmp

   echo "Currently plotting number ${i} of ${count} and started on ${dt}." |tee -a ${log}/${tmp}_${dt}_plot-${i}.log
   echo "Log file name is ${log}/${tmp}_${dt}_plot-${i}.log."
   /opt/chia-plotter/build/chia_plot \
   -r ${threads} \
   -u ${buckets} \
   -v ${buckets3} \
   -t ${tempdir} \
   -d ${dest} \
   -p ${pool} \
   -f ${farm} \
   -G ${tmptoggle} \
   |tee -a ${log}/${tmp}_${dt}_plot-${i}.log
   echo "Time plot $i finished is $(date '+%H:%M:%S')." |tee -a ${log}/${tmp}_${dt}_plot-${i}.log
done